const db = wx.cloud.database();
const qsbdcHost = "http://sound.yywz123.com/qsbdcword/";
const parseWordTestJson = str => {
  let wordTest = JSON.parse(str);
  console.info(wordTest);
  let optionItems = wordTest.items;
  let rightOption =null;

  if(optionItems)
  {
    var a,b,c,d,word;
    a = optionItems[0].explain;
    b = optionItems[1].explain;
    c = optionItems[2].explain;
    d = optionItems[3].explain;

    word = wordTest.topic.word;
    let rightId = wordTest.topic.id;
    for (var i = 0; i < optionItems.length;i++)
    {
      if (optionItems[i].id == rightId)
        {
          rightOption = i+1;
          break;
        }
    }
  }

 
  var audio = wordTest.topic.src.substring(0, 1) + "/" + wordTest.topic.src+".mp3";
  let newWord =
  {
    "word": word,
    "a": a,
    "b": b,
    "c": c,
    "d": d,
    "right": rightOption,
    "audio": qsbdcHost+audio
  }
  //上传的路径
  let cloudPath = "word_test/" + word.substring(0, 1) + "/" + word+".mp3";

  //下载后上传
  wx.downloadFile({
    url: qsbdcHost + audio, // 文件 ID
    success: res => {
      // 返回临时文件路径
      wx.cloud.uploadFile({
        cloudPath: cloudPath, // 上传至云端的路径
        filePath: res.tempFilePath, // 小程序临时文件路径
        success: res => {
          // 返回文件 ID
          console.log(res.fileID)
          newWord.fileID = res.fileID;
          //保存
          db.collection("word_test").add({
            data: newWord,
            success: res => {

            },
            fail: e => {

            }
          })

        },
        fail: console.error
      })

    },
    fail: console.error
  })

 

}



module.exports = {
  parseWordTestJson: parseWordTestJson
}
